<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>好友系统测试</title>
    <link rel="stylesheet" href="css/websocket-test.css">
    <style>
        .friend-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .friend-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .friend-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
            color: #666;
        }
        
        .friend-info {
            flex-grow: 1;
        }
        
        .friend-name {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .friend-status {
            font-size: 12px;
            color: #666;
        }
        
        .friend-actions {
            display: flex;
            gap: 5px;
        }
        
        .status-online {
            color: #4caf50;
        }
        
        .status-offline {
            color: #9e9e9e;
        }
        
        .request-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 10px;
        }
        
        .request-info {
            flex-grow: 1;
        }
        
        .request-actions {
            display: flex;
            gap: 5px;
        }
        
        .btn-sm {
            padding: 3px 8px;
            font-size: 12px;
        }
        
        .btn-accept {
            background-color: #4caf50;
            color: white;
            border: none;
        }
        
        .btn-reject {
            background-color: #f44336;
            color: white;
            border: none;
        }
        
        .user-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #666;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .search-form {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .search-input {
            flex-grow: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="page-header">
            <h1>好友系统测试</h1>
            <div class="user-status">
                <div class="user-avatar" id="userAvatar">?</div>
                <span id="userName">未登录</span>
            </div>
        </div>
        <div class="notification notification-info">
            该页面用于测试好友请求发送、接受和好友状态变更
        </div>

        <div class="row">
            <div class="col" style="max-width: 300px;">
                <div class="card">
                    <h2 class="card-header">连接设置</h2>
                    <div class="form-group">
                        <label for="endpoint">WebSocket端点</label>
                        <input type="text" id="endpoint" value="/ChatMessageServer" placeholder="例如 /ChatMessageServer">
                    </div>
                    <div class="form-group">
                        <label for="username">您的用户名</label>
                        <input type="text" id="username" placeholder="输入用户名">
                    </div>
                    <div class="form-group">
                        <button id="connectBtn" class="btn w-100">连接</button>
                        <button id="disconnectBtn" class="btn btn-secondary w-100 mt-2" disabled>断开</button>
                    </div>

                    <div class="mt-3">
                        <div class="d-flex align-items-center">
                            <div id="statusIndicator" class="status-indicator status-offline"></div>
                            <span id="statusText">未连接</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col" style="flex-grow: 2;">
                <div class="card">
                    <h2 class="card-header">添加好友</h2>
                    <form class="search-form">
                        <input type="text" id="friendUsername" class="form-control search-input" placeholder="输入好友用户名">
                        <button type="button" id="addFriendBtn" class="btn btn-primary">发送请求</button>
                    </form>
                </div>
                
                <div class="card mt-3">
                    <h2 class="card-header">好友请求</h2>
                    <div id="friendRequests" class="p-3">
                        <div class="text-muted text-center">没有待处理的好友请求</div>
                    </div>
                </div>
                
                <div class="card mt-3">
                    <h2 class="card-header">我的好友</h2>
                    <div id="friendList" class="p-3">
                        <div class="text-muted text-center">还没有好友</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col">
                <div class="card">
                    <h2 class="card-header d-flex justify-content-between align-items-center">
                        <span>日志</span>
                        <button id="clearLogsBtn" class="btn btn-small btn-secondary">清空日志</button>
                    </h2>
                    <div id="logContainer" class="message-list" style="height: 200px;"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 脚本引入 -->
    <script src="js/websocket-client.js"></script>
    <script>
    // DOM元素
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const endpointInput = document.getElementById('endpoint');
    const usernameInput = document.getElementById('username');
    const statusIndicator = document.getElementById('statusIndicator');
    const statusText = document.getElementById('statusText');
    const logContainer = document.getElementById('logContainer');
    const clearLogsBtn = document.getElementById('clearLogsBtn');
    const userAvatar = document.getElementById('userAvatar');
    const userName = document.getElementById('userName');
    
    const friendUsername = document.getElementById('friendUsername');
    const addFriendBtn = document.getElementById('addFriendBtn');
    const friendRequests = document.getElementById('friendRequests');
    const friendList = document.getElementById('friendList');

    // 变量
    let wsClient = null;
    let friends = {};
    let pendingRequests = [];

    // 页面初始化
    function init() {
        // 从URL参数获取用户名和端点
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('username')) {
            usernameInput.value = urlParams.get('username');
        }
        if (urlParams.has('endpoint')) {
            endpointInput.value = urlParams.get('endpoint');
        }

        // 绑定事件
        connectBtn.addEventListener('click', connect);
        disconnectBtn.addEventListener('click', disconnect);
        clearLogsBtn.addEventListener('click', clearLogs);
        addFriendBtn.addEventListener('click', sendFriendRequest);
    }

    // 连接WebSocket
    function connect() {
        const endpoint = endpointInput.value.trim();
        const username = usernameInput.value.trim();

        if (!endpoint) {
            addLog('错误', 'WebSocket端点不能为空');
            return;
        }

        if (!username) {
            addLog('错误', '用户名不能为空');
            return;
        }

        // 禁用连接按钮
        connectBtn.disabled = true;
        addLog('信息', `尝试连接到 ${endpoint}...`);

        try {
            // 创建WebSocket客户端
            wsClient = new WebSocketClient(endpoint, username, {
                onConnect: handleConnect,
                onDisconnect: handleDisconnect,
                onMessage: handleMessage,
                onError: handleError,
                onReconnect: handleReconnect,
                onReconnectFailed: handleReconnectFailed
            });

            // 连接
            wsClient.connect();
        } catch (error) {
            addLog('错误', `连接初始化失败: ${error.message}`);
            connectBtn.disabled = false;
        }
    }

    // 处理连接成功
    function handleConnect() {
        // 更新UI状态
        statusIndicator.className = 'status-indicator status-online';
        statusText.textContent = '已连接';
        connectBtn.disabled = true;
        disconnectBtn.disabled = false;
        
        // 更新用户信息
        const username = usernameInput.value.trim();
        userName.textContent = username;
        userAvatar.textContent = username.charAt(0).toUpperCase();
        
        addLog('成功', '连接已建立');
        
        // 这里不主动请求好友列表，让服务器推送好友状态变更
    }

    // 处理连接断开
    function handleDisconnect(event) {
        // 更新UI状态
        statusIndicator.className = 'status-indicator status-offline';
        statusText.textContent = '已断开';
        connectBtn.disabled = false;
        disconnectBtn.disabled = true;
        
        // 重置数据
        friends = {};
        pendingRequests = [];
        updateFriendList();
        updateFriendRequests();
        
        addLog('信息', `连接已断开${event.code ? (' (代码: ' + event.code + ')') : ''}`);
    }

    // 处理接收消息
    function handleMessage(message) {
        addLog('收到', `接收到消息类型: ${message.type}`);
        
        switch (message.type) {
            case 'friend_request':
                handleFriendRequest(message);
                break;
            case 'friend_response':
                handleFriendResponse(message);
                break;
            case 'friend_status':
                handleFriendStatus(message);
                break;
            case 'system':
                handleSystemMessage(message);
                break;
            case 'error':
                addLog('错误', message.content);
                break;
        }
    }

    // 处理好友请求
    function handleFriendRequest(message) {
        const fromUser = message.fromUser;
        
        addLog('信息', `收到来自 ${fromUser} 的好友请求`);
        
        // 添加到请求列表
        pendingRequests.push({
            fromUser: fromUser,
            timestamp: message.timestamp || Date.now()
        });
        
        // 更新UI
        updateFriendRequests();
    }

    // 处理好友请求响应
    function handleFriendResponse(message) {
        const fromUser = message.fromUser;
        const accepted = message.content === 'true';
        
        if (accepted) {
            addLog('成功', `${fromUser} 已接受您的好友请求`);
            
            // 更新好友列表
            friends[fromUser] = false; // 初始设置为离线
            updateFriendList();
        } else {
            addLog('信息', `${fromUser} 拒绝了您的好友请求`);
        }
    }

    // 处理好友状态变更
    function handleFriendStatus(message) {
        const fromUser = message.fromUser;
        const isOnline = message.content === 'online';
        
        // 更新好友状态
        friends[fromUser] = isOnline;
        
        addLog('信息', `好友 ${fromUser} ${isOnline ? '上线' : '离线'}`);
        
        // 更新UI
        updateFriendList();
    }

    // 处理系统消息
    function handleSystemMessage(message) {
        addLog('系统', message.content);
        
        // 检查是否是添加好友成功的消息
        if (message.content.includes('已添加') && message.content.includes('为好友')) {
            const username = message.content.split('已添加 ')[1].split(' 为好友')[0];
            
            // 更新好友列表
            if (!friends[username]) {
                friends[username] = false; // 默认离线状态
                updateFriendList();
            }
        }
    }

    // 处理错误
    function handleError(error) {
        addLog('错误', error.message || '发生未知错误');
    }

    // 处理重连尝试
    function handleReconnect(attempt, maxAttempts) {
        statusText.textContent = `正在重连 (${attempt}/${maxAttempts})`;
        statusText.className = 'animate-blink';
        addLog('信息', `尝试重连 (${attempt}/${maxAttempts})...`);
    }

    // 处理重连失败
    function handleReconnectFailed() {
        statusText.textContent = '重连失败';
        statusText.className = '';
        connectBtn.disabled = false;
        addLog('错误', '重连失败，已达到最大尝试次数');
    }

    // 主动断开连接
    function disconnect() {
        if (wsClient) {
            wsClient.disconnect();
        }
    }

    // 发送好友请求
    function sendFriendRequest() {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        const friendName = friendUsername.value.trim();
        
        if (!friendName) {
            addLog('错误', '请输入好友用户名');
            return;
        }
        
        if (friendName === usernameInput.value) {
            addLog('错误', '不能添加自己为好友');
            return;
        }
        
        if (friends[friendName]) {
            addLog('错误', `${friendName} 已经是您的好友`);
            return;
        }
        
        // 发送好友请求
        const message = {
            type: 'friend_request',
            fromUser: usernameInput.value,
            toUser: friendName
        };
        
        wsClient.sendMessage(message);
        
        addLog('发送', `已向 ${friendName} 发送好友请求`);
        
        // 清空输入框
        friendUsername.value = '';
    }

    // 接受好友请求
    function acceptFriendRequest(fromUser) {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        // 发送接受响应
        const message = {
            type: 'friend_response',
            fromUser: usernameInput.value,
            toUser: fromUser,
            content: 'true'
        };
        
        wsClient.sendMessage(message);
        
        // 移除请求
        pendingRequests = pendingRequests.filter(req => req.fromUser !== fromUser);
        
        // 添加到好友列表
        friends[fromUser] = false; // 初始设置为离线
        
        // 更新UI
        updateFriendRequests();
        updateFriendList();
        
        addLog('发送', `已接受 ${fromUser} 的好友请求`);
    }

    // 拒绝好友请求
    function rejectFriendRequest(fromUser) {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        // 发送拒绝响应
        const message = {
            type: 'friend_response',
            fromUser: usernameInput.value,
            toUser: fromUser,
            content: 'false'
        };
        
        wsClient.sendMessage(message);
        
        // 移除请求
        pendingRequests = pendingRequests.filter(req => req.fromUser !== fromUser);
        
        // 更新UI
        updateFriendRequests();
        
        addLog('发送', `已拒绝 ${fromUser} 的好友请求`);
    }

    // 更新好友列表显示
    function updateFriendList() {
        // 清空现有列表
        friendList.innerHTML = '';
        
        const friendCount = Object.keys(friends).length;
        
        if (friendCount === 0) {
            friendList.innerHTML = '<div class="text-muted text-center">还没有好友</div>';
            return;
        }
        
        // 创建好友列表元素
        const friendListEl = document.createElement('div');
        friendListEl.className = 'friend-list';
        
        // 添加每个好友
        for (const [friendName, isOnline] of Object.entries(friends)) {
            const friendItem = document.createElement('div');
            friendItem.className = 'friend-item';
            
            const firstChar = friendName.charAt(0).toUpperCase();
            
            friendItem.innerHTML = `
                <div class="friend-avatar">${firstChar}</div>
                <div class="friend-info">
                    <div class="friend-name">${friendName}</div>
                    <div class="friend-status ${isOnline ? 'status-online' : 'status-offline'}">
                        ${isOnline ? '在线' : '离线'}
                    </div>
                </div>
            `;
            
            friendListEl.appendChild(friendItem);
        }
        
        friendList.appendChild(friendListEl);
    }

    // 更新好友请求显示
    function updateFriendRequests() {
        // 清空现有列表
        friendRequests.innerHTML = '';
        
        if (pendingRequests.length === 0) {
            friendRequests.innerHTML = '<div class="text-muted text-center">没有待处理的好友请求</div>';
            return;
        }
        
        // 添加每个请求
        pendingRequests.forEach(request => {
            const requestItem = document.createElement('div');
            requestItem.className = 'request-item';
            
            const fromUser = request.fromUser;
            const firstChar = fromUser.charAt(0).toUpperCase();
            const time = new Date(request.timestamp).toLocaleString();
            
            requestItem.innerHTML = `
                <div class="friend-avatar">${firstChar}</div>
                <div class="request-info">
                    <div class="friend-name">${fromUser}</div>
                    <div class="friend-status">${time}</div>
                </div>
                <div class="request-actions">
                    <button class="btn btn-sm btn-accept">接受</button>
                    <button class="btn btn-sm btn-reject">拒绝</button>
                </div>
            `;
            
            // 添加事件监听
            const acceptBtn = requestItem.querySelector('.btn-accept');
            const rejectBtn = requestItem.querySelector('.btn-reject');
            
            acceptBtn.addEventListener('click', () => {
                acceptFriendRequest(fromUser);
            });
            
            rejectBtn.addEventListener('click', () => {
                rejectFriendRequest(fromUser);
            });
            
            friendRequests.appendChild(requestItem);
        });
    }

    // 添加日志
    function addLog(level, message) {
        const logItem = document.createElement('div');
        logItem.className = 'message-item animate-fade-in';
        
        const timeStr = new Date().toLocaleTimeString();
        let levelClass = '';
        
        switch (level.toLowerCase()) {
            case '错误':
                levelClass = 'text-danger';
                break;
            case '成功':
                levelClass = 'text-success';
                break;
            case '信息':
                levelClass = 'text-muted';
                break;
            case '系统':
                levelClass = 'text-primary';
                break;
            case '收到':
                levelClass = 'text-success';
                break;
            case '发送':
                levelClass = 'text-primary';
                break;
            default:
                levelClass = '';
        }
        
        logItem.innerHTML = `
            <div class="message-header">
                <span class="message-sender ${levelClass}">[${level}]</span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">${message}</div>
        `;
        
        logContainer.appendChild(logItem);
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // 清空日志
    function clearLogs() {
        logContainer.innerHTML = '';
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html> 